package com.ly.hotel.spainterface.jxd.activity;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.spainterface.jxd.adapter.JxdXFItemPopupAdapter;
import com.ly.hotel.spainterface.jxd.adapter.JxdXFTypeAdapter;
import com.ly.hotel.spainterface.jxd.bean.JxdXFActionBean;
import com.ly.hotel.spainterface.jxd.bean.JxdXFItemBean;
import com.ly.hotel.spainterface.jxd.bean.JxdXFUnitBean;
import com.ly.hotel.spainterface.jxd.bean.JxdXfTypeBean;
import com.ly.hotel.spainterface.jxd.dialog.JxdXFPopupBuyDialog;
import com.ly.hotel.spainterface.jxd.dialog.JxdXFPopupItemDetailsDialog;
import com.ly.hotel.spainterface.nm.bean.NmXFBuyItemBean;
import com.ly.hotel.util.IdChangeUtil;
import com.ly.hotel.util.ProcessWaitingUtil;
import com.ly.hotel.util.ToastUtil;
import com.ly.hotel.view.MlistView;
import com.ly.hotel.webagent.HttpRequest;
import com.ly.hotel.webagent.UdpCallback;
import com.ly.hotel.webagent.UdpClient;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import de.greenrobot.event.EventBus;


/**
 * Created by SHUBEN on 2018/3/29.
 */

public class JxdXFPopupDialog extends Dialog {
    private MyApplication app;

    private static final String TAG = "JxdXFPopupDialog";

    private int type = 0;
    private Context mcontext;

    private String interfaceIp;
    private String interfacePort;
    private boolean bigClass1Tag = true;            // 大类1标识，是否获取数据
    private boolean bigClass2Tag = true;            // 大类2标识，是否获取数据
    private String waiterConfirm = "false";           //是否需要服务员刷卡确认
    private String picRemark = null;                // 图片水印
    private String actionNo = null;                 // 做法编码
    private int goodsCountLimit = 1;                // 单次下单数量
    private String cardType = "ID_10";                // 卡号类型

    private JxdXFTypeAdapter xfTypeListAdapter;

    private MlistView xfTypeListView;

    private List<JxdXfTypeBean> xiaofeiTypeList = new ArrayList<>();
    private JxdXfTypeBean typeSelect = null;
    private JxdXFItemBean itemSelect = null;

    private GridView mGrid;
    private JxdXFItemPopupAdapter mTAdapter;

    private TextView totalText;
    private TextView nameText;
    private TextView remarkText;
    private TextView title;
    private LinearLayout typeDownMore;
    private ImageView itemDownMore;
    private Button exitBt;
    private List<JxdXFItemBean> recycleviewList = new ArrayList<>();

    private int nowClassTag;                     // 消费大类获取当前步骤
    private int totalClassTag;                   // 消费大类获取总步骤

    private String typeHideArr;
    private String typeSortArr;
    private String itemHideArr;
    private JxdXFPopupItemDetailsDialog detailsDialog = null;
    private JxdXFPopupBuyDialog buyDialog = null;

    private List<NmXFBuyItemBean> buyList;

    private Handler handler;



    public static final int GET_TYPE0 = 0;
    public static final int GET_TYPE = 1;
    public static final int GET_ITEM = 2;

    public static final int GET_HAND = 3;
    public static final int GET_WAITER = 4;
    public static final int GET_BUY = 5;
    public static final int GET_TYPE_HIDE = 6;
    public static final int GET_TYPE_SORT = 7;
    public static final int GET_ITEM_HIDE = 8;
    public static final int GET_ITEM_SORT = 9;
    public static final int SET_TYPE_HIDE = 10;
    public static final int SET_TYPE_SORT = 11;
    public static final int SET_ITEM_HIDE = 12;
    public static final int SET_ITEM_SORT = 13;
    public static final int GET_ITEM_DETAILS = 14;;

    public JxdXFPopupDialog(Context context, int theme) {
        super(context, theme);
        mcontext = context;
        app = (MyApplication) mcontext.getApplicationContext();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jxd_popup_xiaofei);
        initInterfaceConf();
        findView();
        setListener();
        getTypeList();
    }


    @Override
    protected void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    //解析接口配置
    private void initInterfaceConf() {
        try {
            DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
            DocumentBuilder dombuilder = domfac.newDocumentBuilder();
            Document doc = dombuilder.parse(new ByteArrayInputStream(MyApplication.pluginCfg.getBytes("utf-8")));
            NodeList obj = doc.getElementsByTagName(MyApplication.interfaceVersion);

            NodeList sysList = ((Element) obj.item(0)).getElementsByTagName("xiaofei");

            if (sysList.getLength() >= 1) {
                NodeList headList = ((Element) sysList.item(0)).getElementsByTagName("ip");
                if (headList.getLength() >= 1 && headList.item(0) != null && headList.item(0).hasChildNodes()) {
                    interfaceIp = headList.item(0).getFirstChild().getNodeValue();
                }

                headList = ((Element) sysList.item(0)).getElementsByTagName("port");
                if (headList.getLength() >= 1 && headList.item(0) != null && headList.item(0).hasChildNodes()) {
                    interfacePort = headList.item(0).getFirstChild().getNodeValue();
                }

                headList = ((Element) sysList.item(0)).getElementsByTagName("waiterconfirm");
                if (headList.getLength() >= 1 && headList.item(0) != null && headList.item(0).hasChildNodes()) {
                    waiterConfirm = headList.item(0).getFirstChild().getNodeValue();
                }

                headList = ((Element) sysList.item(0)).getElementsByTagName("picRemark");
                if (headList.getLength() >= 1 && headList.item(0) != null && headList.item(0).hasChildNodes()) {
                    picRemark = headList.item(0).getFirstChild().getNodeValue();
                }

                headList = ((Element) sysList.item(0)).getElementsByTagName("actionNo");
                if (headList.getLength() >= 1 && headList.item(0) != null && headList.item(0).hasChildNodes()) {
                    actionNo = headList.item(0).getFirstChild().getNodeValue();
                }

                headList = ((Element) sysList.item(0)).getElementsByTagName("bigclass1");
                if (headList.getLength() >= 1 && headList.item(0) != null && headList.item(0).hasChildNodes()) {
                    if(headList.item(0).getFirstChild().getNodeValue().contains("true")){
                        bigClass1Tag = true;
                    }else{
                        bigClass1Tag = false;
                    }
                }

                headList = ((Element) sysList.item(0)).getElementsByTagName("bigclass2");
                if (headList.getLength() >= 1 && headList.item(0) != null && headList.item(0).hasChildNodes()) {
                    if(headList.item(0).getFirstChild().getNodeValue().contains("true")){
                        bigClass2Tag = true;
                    }else{
                        bigClass2Tag = false;
                    }
                }

                headList = ((Element) sysList.item(0)).getElementsByTagName("goodsCountLimit");
                if (headList.getLength() >= 1 && headList.item(0) != null && headList.item(0).hasChildNodes()) {
                    try {
                        goodsCountLimit = Integer.parseInt(headList.item(0).getFirstChild().getNodeValue());
                    }catch (NumberFormatException e){
                        Log.e(TAG,"goodsCountLimit配置有误");
                    }
                }

                headList = ((Element) sysList.item(0)).getElementsByTagName("cardtype");
                if (headList.getLength() >= 1 && headList.item(0) != null && headList.item(0).hasChildNodes()) {
                    cardType = headList.item(0).getFirstChild().getNodeValue();
                }
            }
        } catch (Exception e) {
            ToastUtil.showShortToast(mcontext, "插件配置有误！", 5000);
        }
    }

    private void findView() {
        mGrid = findViewById(R.id.xfPopVodGridView);
        totalText =  findViewById(R.id.xf_count);
        nameText =  findViewById(R.id.xf_count_name);
        remarkText =  findViewById(R.id.xf_remark_name);
        xfTypeListView = findViewById(R.id.popXfTypeListView);
        typeDownMore =  findViewById(R.id.down_more);
        itemDownMore = findViewById(R.id.xf_down_more);
        title = findViewById(R.id.popup_name);
        title.setText(R.string.naviXiaofeiName);
        exitBt = findViewById(R.id.popup_back);
    }

    private void setListener() {
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what == GET_TYPE_HIDE || msg.what == GET_TYPE_SORT ||
                        msg.what == GET_ITEM_HIDE || msg.what == GET_ITEM_SORT){
                    parseResData(msg.obj.toString(), msg.arg1,msg.what);
                }else{
                    parseResData(msg.what, msg.obj.toString(), msg.arg1);
                }
            }
        };

        exitBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        xfTypeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
                JxdXFTypeAdapter.ViewHolder holder = (JxdXFTypeAdapter.ViewHolder) view.getTag();
                xfTypeListAdapter.setSelectedPosition(pos);
                if (typeSelect != holder.v) {
                    typeSelect = holder.v;
                    ProcessWaitingUtil.showProcessDialog(app,"Loading...",5000);
                    // 有数据就请求SPA服务器估清和排序数据
                    String iId = holder.v.getNo();
                    if (typeSelect.getTypeItems() != null) {
                        toHttpGet(GET_ITEM_HIDE,iId);
                    } else {// 没数据就请求接口服务器数据
                        //清空掉，这样不会有残留上一个分类的数据
                        if (recycleviewList != null) {
                            recycleviewList.clear();
                        }
                        toUdpGet(GET_ITEM, iId, null, null,null);
                    }
                }
            }
        });

        xfTypeListView.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView arg0, int arg1) {
                // TODO Auto-generated method stub
            }

            /* (non-Javadoc)
             * @see android.widget.AbsListView.OnScrollListener#onScroll(android.widget.AbsListView, int, int, int)
             */
            @Override
            public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub
                if ((arg1 == 0 && arg2 == arg3) || (arg1 > 0 && arg1 + arg2 == arg3)) {
                    typeDownMore.setVisibility(View.GONE);
                } else {
                    typeDownMore.setVisibility(View.VISIBLE);
                }
            }
        });

        mGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ProcessWaitingUtil.showProcessDialog(app,"Loading...",5000);
                itemSelect = recycleviewList.get(position);
                if(itemSelect.getAction() != null){
                    showItemDialog(itemSelect);
                }else{
                    toUdpGet(GET_ITEM_DETAILS,itemSelect.getTypeno(),itemSelect.getName(),null,null);
                }
            }
        });

        mGrid.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == 0) {
                    ImageLoader.getInstance().resume();
                } else {
                    ImageLoader.getInstance().pause();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if((firstVisibleItem + visibleItemCount) == totalItemCount){
                    itemDownMore.setVisibility(View.INVISIBLE);
                }else{
                    itemDownMore.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    //消费类别
    private void getTypeList() {
        if(bigClass1Tag || bigClass2Tag) {
            typeSelect = null;
            xiaofeiTypeList.clear();
            if (app.jxdXfTypeBeanList.size() == 0) {
                nowClassTag = 0;
                totalClassTag = 0;
                if(bigClass1Tag){
                    totalClassTag++;
                    toUdpGet(GET_TYPE0, null, null, null,null);
                }
                if(bigClass2Tag){
                    totalClassTag++;
                    toUdpGet(GET_TYPE, null, null, null, null);
                }
            } else {
                toHttpGet(GET_TYPE_HIDE, null);
            }
        }else{
            ToastUtil.showShortToast(mcontext, "项目已屏蔽", 5000);
        }
    }

    //获取服务器存储数据，类别的排序，估清，项目的
    private void toHttpGet(int type,final String typeId){
        switch (type) {
            case GET_TYPE_HIDE:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String URL = MyApplication.getHostResUrl() + "/api/dbfile-read.json";
                        String request = "filename=JXD_XFClassHide";
                        Log.i("httpGet", URL + "?" + request);
                        String sendRes = HttpRequest.sendGet(URL, request);
                        Message msg = new Message();
                        msg.what = GET_TYPE_HIDE;
                        msg.obj = sendRes;
                        handler.sendMessage(msg);
                    }
                }).start();
                break;
            case GET_TYPE_SORT:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String URL = MyApplication.getHostResUrl() + "/api/dbfile-read.json";
                        String request = "filename=JXD_XFClassSort";
                        Log.i("httpGet", URL + request);
                        String sendRes = HttpRequest.sendGet(URL, request);
                        Message msg = new Message();
                        msg.what = GET_TYPE_SORT;
                        msg.obj = sendRes;
                        handler.sendMessage(msg);
                    }
                }).start();
                break;
            case GET_ITEM_HIDE:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String URL = MyApplication.getHostResUrl() + "/api/dbfile-read.json";
                        String request = "filename=JXD_XFItemHide";
                        Log.i("httpGet", URL + "?" + request);
                        String sendRes = HttpRequest.sendGet(URL, request);

                        int id = 0;
                        try {
                            id = Integer.parseInt(typeId);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        Message msg = new Message();
                        msg.what = GET_ITEM_HIDE;
                        msg.arg1 = id;
                        msg.obj = sendRes;
                        handler.sendMessage(msg);
                    }
                }).start();
                break;
            case GET_ITEM_SORT:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String URL = MyApplication.getHostResUrl() + "/api/dbfile-read.json";
                        String request = "filename=JXD_XFItemSort" + typeId;
                        Log.i("httpGet", URL + request);
                        String sendRes = HttpRequest.sendGet(URL, request);
                        int id = 0;
                        try {
                            id = Integer.parseInt(typeId);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }

                        Message msg = new Message();
                        msg.what = GET_ITEM_SORT;
                        msg.arg1 = id;
                        msg.obj = sendRes;
                        handler.sendMessage(msg);
                    }
                }).start();
                break;
        }
    }

    //接口的udp请求
    private void toUdpGet(final int type, final String typeId, final String itemName, final String cardId, final String keyno) {
        new Thread() {
            public void run() {
                final Message msg = new Message();
                msg.what = type;
                msg.arg1 = 0;
                String request = "";
                switch (type) {
                    case GET_TYPE0:
                        request = "<gs ver=\"1.0\" function=\"桑拿消费项目大类查询\" mode = \"request\"><ItemClassName>" +
                                "</ItemClassName><ItemClassNo></ItemClassNo><Attribute>0</Attribute></gs>";
                        break;
                    case GET_TYPE:
                        request = "<gs ver=\"1.0\" function=\"桑拿消费项目大类查询\" mode = \"request\"><ItemClassName>" +
                                "</ItemClassName><ItemClassNo></ItemClassNo><Attribute>1</Attribute></gs>";
                        break;
                    case GET_ITEM:
                        request = "<gs ver=\"1.0\" function=\"桑拿消费项目查询\" mode = \"request\"><itemname></itemname>" +
                                "<itemtypeno>" + typeId + "</itemtypeno></gs>";
                        break;
                    case GET_ITEM_DETAILS:
                        request = "<gs ver=\"1.0\" function=\"桑拿消费项目查询\" mode = \"request\"><itemname>" + itemName + "</itemname>" +
                                "<itemtypeno>" + typeId + "</itemtypeno></gs>";
                        break;
                    case GET_HAND:
                        request = "<gs ver=\"1.0\" function=\"桑拿卡号转匙牌号\" mode = \"request\"><ArtFlag>0</ArtFlag>" +
                                "<RfCardno>" + cardId + "</RfCardno></gs>";
                        break;
                    case GET_BUY:
                        request = "<gs ver=\"1.0\" function=\"桑拿消费下单\" mode = \"request\">";
                        String roomNo = MyApplication.getDeviceInfo().getName();
                        for (NmXFBuyItemBean bb : buyList){
                            request += "<item><RoomNo>" + roomNo + "</RoomNo><KeyNo>" + keyno + "</KeyNo><Code>" + bb.getId()
                                    + "</Code><Quantity>" + bb.getNum() + "</Quantity><ActionNo>" + bb.getActionNo() +
                                    "</ActionNo><OperCardId>" + cardId + "</OperCardId><UnitName>" + bb.getUnit() +
                                    "</UnitName></item>";
                        }
                        request += "</gs>";
                        break;
                }
                Log.d("udp", interfaceIp + "," + interfacePort + "," + request );
                UdpCallback c = new UdpCallback() {
                    @Override
                    public void receive(String s) {
                        if(type == GET_TYPE0 || type == GET_TYPE) {
                            nowClassTag++;
                        }
                        //返回的数据需要去掉\r\n,\n这些字符，否则会影响数据的处理
                        msg.obj = s.replace("\r\n", "").replace("'", "’");
                        handler.sendMessage(msg);
                    }
                };
                try {
                    int p = Integer.parseInt(interfacePort);
                    new UdpClient(interfaceIp, p, c, "<gs", "</gs>", "Msg").send(request);
                } catch (NumberFormatException n) {
                    Log.e(TAG, "插件端口转换出错");
                    msg.obj = "";
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    msg.obj = "";
                    handler.sendMessage(msg);
                }
            }
        }.start();
    }

    //解析接口服务器数据
    private void parseResData(int type, String parseStr,int tid) {
        if(!TextUtils.isEmpty(parseStr)) {
            try {
                if (!parseStr.startsWith("Msg")) {
                    DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
                    DocumentBuilder dombuilder = domfac.newDocumentBuilder();
                    Document doc = dombuilder.parse(new ByteArrayInputStream(parseStr.getBytes("utf-8")));
                    NodeList obj = doc.getElementsByTagName("gs");
                    NodeList dataList;

                    if (type == GET_TYPE0 || type == GET_TYPE) {
                        dataList = ((Element) obj.item(0)).getElementsByTagName("row");
                        for (int i = 0; i < dataList.getLength(); i++) {
                            NodeList noList = ((Element) dataList.item(i)).getElementsByTagName("itemclassno");
                            NodeList nameList = ((Element) dataList.item(i)).getElementsByTagName("itemclassname");
                            NodeList markList = ((Element) dataList.item(i)).getElementsByTagName("remark");
                            String no = "";
                            String name = "";
                            String remark = "";
                            if (noList.getLength() >= 1 && noList.item(0) != null && noList.item(0).hasChildNodes()) {
                                no = noList.item(0).getFirstChild().getNodeValue();
                            }

                            if (nameList.getLength() >= 1 && nameList.item(0) != null && nameList.item(0).hasChildNodes()) {
                                name = nameList.item(0).getFirstChild().getNodeValue();
                            }
                            if (markList.getLength() >= 1 && markList.item(0) != null && markList.item(0).hasChildNodes()) {
                                remark = markList.item(0).getFirstChild().getNodeValue();
                            }
                            JxdXfTypeBean tb = new JxdXfTypeBean(type);
                            tb.setNo(no);
                            tb.setName(name);
                            tb.setMark(remark);
                            if (!TextUtils.isEmpty(no)) {
                                app.jxdXfTypeBeanList.add(tb);
                            }
                        }
                        if (nowClassTag == totalClassTag) {
                            toHttpGet(GET_TYPE_HIDE, null);
                        }
                    } else {
                        switch (type) {
                            case GET_ITEM:
                                dataList = ((Element) obj.item(0)).getElementsByTagName("row");

                                for (int i = 0; i < dataList.getLength(); i++) {
                                    NodeList noList = ((Element) dataList.item(i)).getElementsByTagName("itemno");
                                    NodeList nameList = ((Element) dataList.item(i)).getElementsByTagName("itemname");
                                    NodeList unitList = ((Element) dataList.item(i)).getElementsByTagName("unitname");
                                    NodeList priceList = ((Element) dataList.item(i)).getElementsByTagName("price");
                                    NodeList tNoList = ((Element) dataList.item(i)).getElementsByTagName("v_dishno1");
                                    String no = "";
                                    String name = "";
                                    String unit = "";
                                    String price = "";
                                    String typeNo = "";
                                    if (noList.getLength() >= 1 && noList.item(0) != null && noList.item(0).hasChildNodes()) {
                                        no = noList.item(0).getFirstChild().getNodeValue();
                                    }

                                    if (nameList.getLength() >= 1 && nameList.item(0) != null && nameList.item(0).hasChildNodes()) {
                                        name = nameList.item(0).getFirstChild().getNodeValue();
                                    }
                                    if (unitList.getLength() >= 1 && unitList.item(0) != null && unitList.item(0).hasChildNodes()) {
                                        unit = unitList.item(0).getFirstChild().getNodeValue();
                                    }
                                    if (priceList.getLength() >= 1 && priceList.item(0) != null && priceList.item(0).hasChildNodes()) {
                                        price = priceList.item(0).getFirstChild().getNodeValue();
                                    }
                                    if (tNoList.getLength() >= 1 && tNoList.item(0) != null && tNoList.item(0).hasChildNodes()) {
                                        typeNo = tNoList.item(0).getFirstChild().getNodeValue();
                                    }
                                    JxdXFItemBean tb = new JxdXFItemBean();
                                    tb.setNo(no);
                                    tb.setName(name);
                                    tb.setUnit(unit);
                                    tb.setPrice(price);
                                    tb.setTypeno(typeNo);
                                    if (!TextUtils.isEmpty(no)) {
                                        typeSelect.setTypeItems(tb);
                                    }
                                }
                                toHttpGet(GET_ITEM_HIDE, typeSelect.getNo());
                                break;
                            case GET_ITEM_DETAILS:
                                dataList = ((Element) obj.item(0)).getElementsByTagName("row");
                                List<JxdXFActionBean> aList = new ArrayList<>();
                                List<JxdXFUnitBean> uList = new ArrayList<>();
                                for (int i = 0; i < dataList.getLength(); i++) {
                                    NodeList noList = ((Element) dataList.item(i)).getElementsByTagName("itemno");
                                    String no = "";
                                    if (noList.getLength() >= 1 && noList.item(0) != null && noList.item(0).hasChildNodes()) {
                                        no = noList.item(0).getFirstChild().getNodeValue();
                                    }
                                    if(itemSelect.getNo().equals(no)){
                                        NodeList actionList = ((Element) dataList.item(i)).getElementsByTagName("Action");
                                        NodeList unitList = ((Element) dataList.item(i)).getElementsByTagName("ItemPrice");
                                        if (actionList.getLength() >= 1 ) {
                                            for (int j =0;j<actionList.getLength();j++){
                                                try {
                                                    NodeList aNameList = ((Element) actionList.item(j)).getElementsByTagName("Name");
                                                    NodeList aNoList = ((Element) actionList.item(j)).getElementsByTagName("No");
                                                    String aName = "";
                                                    String aNo = "";
                                                    if (aNameList.getLength() >= 1 && aNameList.item(0) != null && aNameList.item(0).hasChildNodes()) {
                                                        aName = aNameList.item(0).getFirstChild().getNodeValue();
                                                    }
                                                    if (aNoList.getLength() >= 1 && aNoList.item(0) != null && aNoList.item(0).hasChildNodes()) {
                                                        aNo = aNoList.item(0).getFirstChild().getNodeValue();
                                                    }
                                                    if (!TextUtils.isEmpty(aNo)) {
                                                        JxdXFActionBean ab = new JxdXFActionBean();
                                                        ab.setA_name(aName);
                                                        ab.setA_no(aNo);
                                                        aList.add(ab);
                                                    }
                                                }catch (Exception e){
                                                    Log.e(TAG,"做法解析出错：" + e.getMessage());
                                                }
                                            }

                                        }
                                        if (unitList.getLength() >= 1 ) {
                                            for (int k =0;k<unitList.getLength();k++){
                                                try {
                                                    NodeList uNameList = ((Element) unitList.item(k)).getElementsByTagName("Unit");
                                                    NodeList uPriceList = ((Element) unitList.item(k)).getElementsByTagName("Pri");
                                                    String uName = "";
                                                    String uPrice = "";
                                                    if (uNameList.getLength() >= 1 && uNameList.item(0) != null && uNameList.item(0).hasChildNodes()) {
                                                        uName = uNameList.item(0).getFirstChild().getNodeValue();
                                                    }
                                                    if (uPriceList.getLength() >= 1 && uPriceList.item(0) != null && uPriceList.item(0).hasChildNodes()) {
                                                        uPrice = uPriceList.item(0).getFirstChild().getNodeValue();
                                                    }
                                                    if (!TextUtils.isEmpty(uPrice)) {
                                                        JxdXFUnitBean ub = new JxdXFUnitBean();
                                                        ub.setUnitName(uName);
                                                        ub.setUnitPrice(uPrice);
                                                        uList.add(ub);
                                                    }
                                                }catch (Exception e){
                                                    Log.e(TAG,"单位解析出错：" + e.getMessage());
                                                }
                                            }
                                        }
                                    }
                                }

                                itemSelect.setAction(aList);
                                itemSelect.setUnitBeen(uList);
                                showItemDialog(itemSelect);
                                break;
                            case GET_HAND:
                                dataList = ((Element) obj.item(0)).getElementsByTagName("keyno");
                                String errmsg = mcontext.getString(R.string.xf_call_waiter);
                                String keyNo = "";
                                if (dataList.getLength() >= 1 && dataList.item(0) != null && dataList.item(0).hasChildNodes()) {
                                    keyNo = dataList.item(0).getFirstChild().getNodeValue();
                                }
                                if(!TextUtils.isEmpty(keyNo)){
                                    senBuyDialogMsg(1, true, keyNo);
                                }else{
                                    senBuyDialogMsg(1, false, errmsg);
                                }
                                break;
                            case GET_BUY:
                                NodeList rcList = ((Element) obj.item(0)).getElementsByTagName("rc");
                                String rc = "";
                                if (rcList.getLength() >= 1 && rcList.item(0) != null && rcList.item(0).hasChildNodes()) {
                                    rc = rcList.item(0).getFirstChild().getNodeValue();
                                }
                                if(rc.equals("0")){
                                    if(detailsDialog.isShowing()){
                                        detailsDialog.dismiss();
                                    }
                                    senBuyDialogMsg(true,"");
                                    EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_XIAOFEI + "\t" +
                                            MyApplication.interfaceVersion + "\t" + "下单成功"));
                                }else{
                                    senBuyDialogMsg(false,"");
                                }
                            default:
                                break;
                        }
                    }
                }else{
                    if (type == GET_HAND) {
                        senBuyDialogMsg(1, false, parseStr);
                    } else if (type == GET_BUY) {
                        senBuyDialogMsg(false,parseStr);
                    } else {
                        ToastUtil.showShortToast(mcontext, parseStr, 5000);
                    }
                }
            }catch (Exception e){
                String errmsg = "数据解析出错！";
                if (type == GET_HAND) {
                    senBuyDialogMsg(1, false, errmsg);
                } else if (type == GET_BUY) {
                    senBuyDialogMsg(false,errmsg);
                } else {
                    ToastUtil.showShortToast(mcontext, errmsg, 5000);
                }
            }
        } else {
            String errmsg = mcontext.getString(R.string.connect_err);
            if (type == GET_HAND) {
                senBuyDialogMsg(1, false, errmsg);
            } else if (type == GET_BUY) {
                senBuyDialogMsg(false,"");
            } else {
                ToastUtil.showShortToast(mcontext, errmsg, 5000);
            }
        }
    }

    //解析SPA服务器数据
    private void parseResData(String parseStr,int tid,int type) {
        switch (type) {
            case GET_TYPE_HIDE:
                try {
                    JSONObject jsobj = new JSONObject(parseStr);
                    int code = jsobj.getInt("code");
                    String data = jsobj.getString("data");
                    if (code == 200 && !TextUtils.isEmpty(data)) {
                        typeHideArr = data;
                    }else{
                        typeHideArr = null;
                    }
                } catch (JSONException e) {
                    typeHideArr = null;
                    Log.e(TAG,e.getMessage());
                }
                toHttpGet(GET_TYPE_SORT,null);
                break;
            case GET_TYPE_SORT:
                try {
                    JSONObject jsobj = new JSONObject(parseStr);
                    int code = jsobj.getInt("code");
                    String data = jsobj.getString("data");
                    if (code == 200 && !TextUtils.isEmpty(data)) {
                        typeSortArr = data;
                    }else{
                        typeSortArr = null;
                    }
                } catch (JSONException e) {
                    typeSortArr = null;
                    Log.e(TAG,e.getMessage()+"");
                }
                updateTypeList();
                updateTypeListView();
                break;
            case GET_ITEM_HIDE:
                try {
                    JSONObject jsobj = new JSONObject(parseStr);
                    int code = jsobj.getInt("code");
                    String data = jsobj.getString("data");
                    if (code == 200 && !TextUtils.isEmpty(data)) {
                        itemHideArr = data;
                    }else{
                        itemHideArr = null;
                    }
                } catch (JSONException e) {
                    itemHideArr = null;
                }
                toHttpGet(GET_ITEM_SORT,typeSelect.getNo());
                break;
            case GET_ITEM_SORT:
                try {
                    JSONObject jsobj = new JSONObject(parseStr);
                    int code = jsobj.getInt("code");
                    String data = jsobj.getString("data");
                    if (code == 200 && !TextUtils.isEmpty(data)) {
                        typeSelect.setSortItems(data);
                    }else{
                        typeSelect.setSortItems(null);
                    }
                } catch (JSONException e) {
                    typeSelect.setSortItems(null);
                }
                updateXFItemList(typeSelect);
                updateXFItemView();
                break;
            default:
                break;
        }
    }

    private void updateTypeList(){
        xiaofeiTypeList.clear();
        if(!TextUtils.isEmpty(typeSortArr)){
            try {
                JSONArray arr = new JSONArray(typeSortArr);
                for (int i = arr.length() -1; i >= 0; i--) {
                    String lan = arr.getString(i);
                    for (JxdXfTypeBean b : app.jxdXfTypeBeanList) {
                        if(lan.equals(b.getNo())) {
                            app.jxdXfTypeBeanList.remove(b);
                            app.jxdXfTypeBeanList.add(0,b);
                            break;
                        }
                    }
                }
            }catch (JSONException e){
                Log.e(TAG,e.getMessage());
            }
        }

        if(!TextUtils.isEmpty(typeHideArr)) {
            for (JxdXfTypeBean b : app.jxdXfTypeBeanList) {
                if (!typeHideArr.contains(b.getNo())) {
                    b.setShow(true);
                    xiaofeiTypeList.add(b);
                } else {
                    b.setShow(false);
                }
            }
        }else{
            xiaofeiTypeList.addAll(app.jxdXfTypeBeanList);
        }
    }

    private void updateTypeListView() {
        // 使用自定义的Adapter
        if(xfTypeListAdapter == null) {
            xfTypeListAdapter = new JxdXFTypeAdapter(mcontext, xiaofeiTypeList);
            xfTypeListView.setAdapter(xfTypeListAdapter);
        }else{
            xfTypeListAdapter.notifyDataSetChanged();
        }

        if (xiaofeiTypeList.size() >= 1) {
            //模拟第一行点击
            xfTypeListView.post(new Runnable() {
                public void run() {
                    int count = xfTypeListView.getChildCount();
                    if (count != 0) {
                        xfTypeListView.performItemClick(xfTypeListView.getChildAt(0),
                                0, xfTypeListView.getItemIdAtPosition(0));
                        xfTypeListView.requestFocus();
                        xfTypeListView.requestFocusFromTouch();
                        xfTypeListView.setSelection(0);
                    }
                }

            });
        }
    }

    private void updateXFItemList(JxdXfTypeBean itempart) {
        if (itempart.getTypeItems() != null) {
            List<JxdXFItemBean> list = itempart.getTypeItems();
            recycleviewList.clear();
            String sortItems = itempart.getSortItems();
            if(!TextUtils.isEmpty(sortItems)){
                try {
                    JSONArray arr = new JSONArray(sortItems);
                    for (int i = arr.length() -1; i >= 0; i--) {
                        String lan = arr.getString(i);
                        for (JxdXFItemBean b : list) {
                            if(lan.equals(b.getNo())) {
                                list.remove(b);
                                list.add(0,b);
                                break;
                            }
                        }
                    }
                }catch (JSONException e){
                    Log.e(TAG,"项目排序出错");
                }
            }

            if(!TextUtils.isEmpty(itemHideArr)){
                for(JxdXFItemBean lb:list) {
                    if (!itemHideArr.contains(lb.getNo())){
                        lb.setShow(true);
                        recycleviewList.add(lb);
                    }else{
                        lb.setShow(false);
                    }
                }
            }else{
                recycleviewList.addAll(list);
            }
        }
    }

    private void updateXFItemView() {
        if (recycleviewList != null && typeSelect != null) {
            nameText.setText(typeSelect.getName());
            totalText.setText(recycleviewList.size() + "");
            if(TextUtils.isEmpty(typeSelect.getMark())){
                remarkText.setText("");
                remarkText.setVisibility(View.GONE);
            }else{
                remarkText.setText("(" + typeSelect.getMark() + ")");
                remarkText.setVisibility(View.VISIBLE);
            }
        }
        if (mTAdapter == null) {
            mTAdapter = new JxdXFItemPopupAdapter(mcontext,recycleviewList);
            mGrid.setAdapter(mTAdapter);
        } else {
            mTAdapter.notifyDataSetChanged();
        }
        mGrid.post(new Runnable() {
            @Override
            public void run() {
                ProcessWaitingUtil.closeProcessDialog();
                mGrid.setSelection(0);
            }
        });
        if (recycleviewList.size() < 9) {
            itemDownMore.setVisibility(View.INVISIBLE);
        }else{
            itemDownMore.setVisibility(View.VISIBLE);
        }
    }

    //显示消费详情
    public void showItemDialog(JxdXFItemBean item) {
        ProcessWaitingUtil.closeProcessDialog();
        /*if (detailsDialog == null) {
            detailsDialog = new JxdXFPopupItemDetailsDialog(mcontext, R.style.introDialog);
            detailsDialog.setCanceledOnTouchOutside(true);
            detailsDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
        }

        detailsDialog.show();
        detailsDialog.initData(item);*/
        EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_XIAOFEI + "\t" +
                MyApplication.interfaceVersion + "\t" + "商品详情"));
    }

    //刷卡下单弹窗
    public void showBuyDialog(List<NmXFBuyItemBean> bl){
        /*if(buyDialog == null){
            buyDialog = new JxdXFPopupBuyDialog(this,R.style.introDialog);
            buyDialog.setCanceledOnTouchOutside(false);
            buyDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
        }
        buyDialog.show();
        buyDialog.initData(bl);*/
    }

    //给购买页面发送数据
    private void senBuyDialogMsg(int type,boolean tag,String msg){
        if (!buyDialog.isShowing()){
            buyDialog.show();
        }
        buyDialog.onCardBack(type, tag, msg);
    }

    //给购买页面发送下单结果
    private void senBuyDialogMsg(boolean tag, String msg){
        ProcessWaitingUtil.closeProcessDialog();
        if (!buyDialog.isShowing()){
            buyDialog.show();
        }
        buyDialog.onBuyBack(tag, msg);
    }

    //获取单次最大购买数量
    public int getMaxBuyCount(){
        return goodsCountLimit;
    }

    //获取图片备注
    public String getPicRemark() {
        return picRemark;
    }


    //dialog获取是否需要服务员确认接口
    public String getWaiterConfirm(){
        return waiterConfirm;
    }

    public String getCardtype() {
        return cardType;
    }

    //buydialog刷卡请求事件
    public void requestCard(int type,String cardId) {
        String id = IdChangeUtil.getId(cardId,cardType);
        Log.i(TAG, "查询卡号，oldid=" + cardId + "&newid=" + id);
        switch (type) {
            case 1:
                toUdpGet(GET_HAND, null, null, id, null);
                break;
        }
    }

    //buydialog下单事件
    public void requestBuy(List<NmXFBuyItemBean> by,String keyno,String waiter){
        ProcessWaitingUtil.showProcessDialog(app,"Loading...",5000);
        Log.i(TAG, "下单，keyno=" + keyno);
        buyList = by;
        toUdpGet(GET_BUY, null, null, waiter, keyno);
    }
}